<template>
  <el-scrollbar v-loading="loading" class="p-4 pb-0">
    <div class="mb-6">
      <el-radio-group v-model="todoType">
        <el-radio-button :label="1">操作方式1</el-radio-button>
        <el-radio-button :label="2">操作方式2</el-radio-button>
      </el-radio-group>
    </div>
    <domain-add-form
      v-if="todoType === 1"
      ref="domainAddFormRef"
      :loading="loading"
      :form-state="formState"
      :main-submit="handleSubmit"
    />
    <log-todo-form2
      v-else
      ref="logTodoForm2Ref"
      :loading="loading"
      :form-state="formState2"
      :main-submit="handleSubmit"
    />
    <add-log-error-dialog
      v-model:visible="errorDialogVisible"
      :state="errorState"
    />
    <add-log-error-dialog2
      v-model:visible="errorDialog2Visible"
      :state="error2State"
    />
  </el-scrollbar>
</template>

<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import type { Ref } from 'vue'

import type { UserModel } from '@/apis/model/user'

import DomainAddForm from '../components/DomainAddForm.vue'
import LogTodoForm2 from '../components/LogTodoForm2.vue'
import AddLogErrorDialog from '../dialogs/batch/AddLogErrorDialog.vue'
import AddLogErrorDialog2 from '../dialogs/batch/AddLogErrorDialog2.vue'
import type { IBatchActive, RrsItem, SubmitBtnUpdateFn } from '../type'
import { SUBMIT_BTN_UPDATE } from '../utils/constants'

const todoType = ref(1)

const formRef = ref<FormInstance>()
const formState = reactive({
  domains: '',
  rrs: [] as RrsItem[]
})

const formState2 = reactive({
  rrs: ''
})

const domainAddFormRef = ref<InstanceType<typeof DomainAddForm>>()
const logTodoForm2Ref = ref<InstanceType<typeof LogTodoForm2>>()

const user = inject('user') as Ref<UserModel>

const updateSubmitBtn = inject(SUBMIT_BTN_UPDATE) as SubmitBtnUpdateFn
const active = inject('active') as Ref<IBatchActive>

watchPostEffect(() => {
  if (active.value === '批量添加记录') {
    updateSubmitBtn({
      onSubmit:
        todoType.value === 1
          ? domainAddFormRef.value?.submit!
          : logTodoForm2Ref.value?.submit!
    })
  }
})

watchEffect(() => {
  updateSubmitBtn({
    disabled: todoType.value === 1 ? !formState.domains : !formState2.rrs
  })
})

const errorDialogVisible = ref(false)
const errorDialog2Visible = ref(false)

const errorState = reactive({
  success_count: '0',
  fail_domains: [] as string[],
  domain_count: '0'
})

const error2State = reactive({
  success_count: '0',
  rr_count: '0',
  fail_domains: [] as string[]
})

const domains = computed(() => getTrimValue(formState.domains))

const loading = ref(false)

watch(loading, val => updateSubmitBtn({ loading: val }))

async function handleSubmit() {
  await formRef.value?.validate()
  loading.value = true

  try {
    let res
    let rrs
    if (todoType.value === 1) {
      rrs = formState.rrs
        .map(v => ({ ...v, name: v.name || '@' }))
        .filter(v => v.value)

      res = await addBatchRecordApi({
        user_id: user.value.id!,
        domains: domains.value,
        rrs
      })
    } else {
      rrs = getTrimValue(formState2.rrs)
      res = await addBatchRecord2Api({ user_id: user.value.id!, rrs })
    }

    let isError: boolean = false
    if (todoType.value === 1) {
      const successRrCount = +(res.success_count ?? '0')
      const domainTotalCount = +(res.domain_count ?? '0')
      const rrsTotalCount = rrs?.length ?? 0
      isError = domainTotalCount * rrsTotalCount !== successRrCount
    } else {
      const successRrCount = +(res.success_count ?? '0')
      const rrsTotalCount = +(res.rr_count ?? '0')
      isError = successRrCount !== rrsTotalCount
    }

    if (!res.fail_domains?.length && !isError) {
      ToastUtils.success(
        `<div class="pb-1">添加成功</div>
        <div>共添加${res.success_count}条记录</div>`
      )
    } else {
      if (todoType.value === 1) {
        errorState.success_count = res.success_count ?? '0'
        errorState.fail_domains = res.fail_domains ?? []
        errorState.domain_count = res.domain_count ?? '0'
        errorDialogVisible.value = true
      } else {
        error2State.success_count = res.success_count ?? '0'
        error2State.rr_count = res.rr_count ?? '0'
        error2State.fail_domains = res.fail_domains ?? []
        errorDialog2Visible.value = true
      }
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  const domains = history.state.domains as string[]

  if (domains?.length) {
    formState.domains = domains.join('\n')
  }
  history.state.domains = null
})
</script>

<style lang="scss" scoped>
.el-radio-group {
  .el-radio-button {
    --el-radio-button-checked-bg-color: #f3f6ff;
    --el-radio-button-checked-text-color: #164cff;
  }

  .el-radio-button__original-radio:checked + .el-radio-button__inner {
    border-color: #164cff;
  }
}

:deep(.submit-btn) {
  display: none;
}
</style>
